#pragma once

#include<iostream>
#include<signal.h>
#include<functional>
#include"Sock.hpp"

class HttpServer
{
public:
    using func_t = std::function<void (int)>;
private:
    int _listensock;
    uint16_t _port;
    Sock sock;
    func_t _func;
public:
    HttpServer(const uint16_t &port, func_t func)
    :_port(port)
    ,_func(func)
    {
        _listensock = sock.Socket();
        sock.Bind(_listensock, _port);
        sock.Listen(_listensock);
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        for( ; ; )
        {
            std::string ClientIp;
            uint16_t ClientPort = 0;
            int sockfd = sock.Accept(_listensock, &ClientIp, &ClientPort);
            if(sockfd < 0) continue;

            if(fork() == 0)
            {
                close(_listensock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }

    ~HttpServer()
    {
        if(_listensock >= 0)
            close(_listensock);
    }
};